import {
	Button,
	Collapse,
	Form,
	Input,
	Row,
	Col,
	Tree,
	message,
	TreeSelect,
} from 'antd'
import React, {memo, useEffect, useState} from 'react'
import {history, connect} from 'umi'

import {translateDataToTree} from '@/utils/common/index'
import {getMenuList} from '@/service/system/menu'
import {addRole, editRole, roleCopy, viewRole} from '@/service/system/role'
import styles from '@/assets/common/css/page.less'
import {codePattern} from '@/utils/common/validator'
import {getCompany} from '@/service/common'

const {TextArea} = Input
const {Panel} = Collapse

const addDom = memo(
	(props: {
		user: {currentMerchantId: string | number; orgId: any}
		location: any
	}) => {
		const [form] = Form.useForm()
		const [menuSource, setMenuSource] = useState<any[]>([])
		const [selectIdData, setSelectedIdData] = useState<any>({})
		const [roleId, setRoleIdData] = useState()
		const [typeData, setTypeData] = useState()
		const [checkStrictly, setCheckStrictly] = useState(true)
		// 提交给后端的数据，是带没全选子的父节点id
		const [checkedKeysResult, setCheckedKeysResult] = useState<any[]>([])
		const [companyData, setCompanyData] = useState([]) // 所属公司数据
		const [orgId, setOrgId] = useState<any>() // 公司ID
		/** 获取所属公司数据 */
		const onCompany = () => {
			getCompany({merchantId: props.user?.orgId}).then((res: any) => {
				const list = translateDataToTree(res.data)
				setCompanyData(list as any)
			})
		}
		useEffect(() => {
			onCompany()
		}, [props.user?.orgId])

		// 获取菜单数据
		const onListFun = () =>
			getMenuList().then((res: any) => {
				if (res?.success) {
					return res.data
				}
				return []
			})

		const getValidIdData = (
			list: any,
			res: any = {checked: [], halfChecked: []},
		) => {
			list.forEach((item: any) => {
				if (item.children) {
					// 从底刷一遍 checked 保证准确性
					getValidIdData(item.children, res)
					const checked = item.children.every(
						(child: any) => child.checked,
					)
					// eslint-disable-next-line no-param-reassign
					item.checked = checked
					const halfChecked = item.children.some(
						(child: any) => child.checked || child.halfChecked,
					)
					// eslint-disable-next-line no-param-reassign
					item.halfChecked = halfChecked
					if (checked) {
						res.checked.push(item.id)
					}
					if (halfChecked) {
						res.halfChecked.push(item.id)
					}
				} else if (item.checked) {
					res.checked.push(item.id)
				}
			})
			return res
		}

		// 获取角色详情
		const viewRoleFun = (id: string, flatList: any) => {
			// 第一次渲染时也要存储传给后端的数据，否则用户不change点保存会清空数据
			const keysResultArr: any[] = []
			// flatList 为全集，permissionList 为有权限的集合，先将两个合并，然后递归遍历，把没有子未全选的父节点id剔除。否则Tree组件认为父节点选中，更新子节点时，其父节点的所有子都被选中
			viewRole(id).then((res: any) => {
				const {permissionList = []} = res?.data || {}
				const addCheckedFlatList = flatList.map((item: any) => {
					const checked = permissionList.some((permission: any) => {
						keysResultArr.push(permission.id)
						return permission.id === item.id
					})
					return {
						...item,
						checked,
					}
				})
				const list = translateDataToTree(addCheckedFlatList)
				const idData = getValidIdData(list)
				setMenuSource(list as any)
				form.setFieldsValue({...res.data})
				setSelectedIdData(idData)
				setCheckedKeysResult(keysResultArr)
				setTimeout(() => {
					setCheckStrictly(() => false)
				}, 300)
			})
		}
		useEffect(() => {
			const {id, type} = props.location.query
			onListFun().then((flatList) => {
				if (id) {
					viewRoleFun(id, flatList)
					setRoleIdData(id)
					setTypeData(type)
				} else {
					const list = translateDataToTree(flatList)
					setMenuSource(list as any)
					setTimeout(() => {
						setCheckStrictly(() => false)
					}, 300)
				}
			})
		}, [])

		const onCheck = (checkedKeys: any, e: any) => {
			setSelectedIdData([...checkedKeys])
			// 保存带有父节点的数据
			setCheckedKeysResult([...checkedKeys, ...e.halfCheckedKeys])
		}

		const onFinish = async () => {
			const fromData = await form.validateFields()
			if (!roleId || typeData === 'copy') {
				// 新增角色
				addRole({
					...fromData,
					permissionIdList: [...checkedKeysResult],
					merchantId: props.user.currentMerchantId,
				}).then((res: any) => {
					if (res.success) {
						if (orgId?.length) {
							// 角色分配公司
							roleCopy({
								sourceRoleId: roleId,
								targetOrgIds: orgId,
							})
						}
						history.go(-1)
						message.success(res.msg)
					}
				})
			} else {
				// 编辑角色
				editRole(roleId, {
					...fromData,
					permissionIdList: [...checkedKeysResult],
				}).then((res: any) => {
					if (res.success) {
						if (orgId?.length) {
							// 角色分配公司
							roleCopy({
								sourceRoleId: roleId,
								targetOrgIds: orgId,
							})
						}
						history.go(-1)
						message.success(res.msg)
					}
				})
			}
		}

		const customizeHeader = (value: string) => (
			<div>
				<div className={styles.tip} />
				{value}
			</div>
		)
		return (
			<div className={styles.page}>
				<div className={`${styles.content} ${styles.formDetils}`}>
					<Collapse
						defaultActiveKey={['1', '2']}
						ghost
						expandIconPosition="end">
						<Panel header={customizeHeader('基础信息')} key="1">
							<Form
								name="basic"
								form={form}
								layout="horizontal"
								labelCol={{style: {width: 80}}}
								initialValues={{remember: true}}
								autoComplete="off">
								<Row gutter={12}>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="编码"
											name="code"
											rules={[
												{
													required: true,
													pattern: codePattern,
													message: '只能输入英文',
												},
											]}>
											<Input
												placeholder="请输入编号"
												maxLength={30}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="名称"
											name="name"
											rules={[
												{
													required: true,
													message: '请输入名称',
												},
											]}>
											<Input
												placeholder="请输入名称"
												maxLength={60}
											/>
										</Form.Item>
									</Col>
									{typeData === 'edit' ? (
										<Col
											sm={{span: 24}}
											md={{span: 16}}
											lg={{span: 16}}>
											<Form.Item
												label="分配公司"
												name="allocationCompany">
												<TreeSelect
													showSearch
													style={{width: '100%'}}
													dropdownStyle={{
														maxHeight: 400,
														overflow: 'auto',
													}}
													placeholder="请选择"
													allowClear
													multiple
													showCheckedStrategy="SHOW_ALL"
													treeDefaultExpandAll
													treeNodeFilterProp="name"
													fieldNames={{
														label: 'name',
														value: 'id',
													}}
													treeDataSimpleMode
													treeData={companyData}
													onChange={(value) => {
														setOrgId(value)
													}}
												/>
											</Form.Item>
										</Col>
									) : (
										''
									)}

									<Col
										sm={{span: 24}}
										md={{span: 16}}
										lg={{span: 16}}>
										<Form.Item
											label="描述"
											name="description">
											<TextArea
												placeholder="请输入( 最多200个字 )"
												maxLength={200}
												autoSize={{
													minRows: 4,
													maxRows: 6,
												}}
											/>
										</Form.Item>
									</Col>
								</Row>
							</Form>
						</Panel>
						<Panel header={customizeHeader('功能授权')} key="2">
							<Tree
								checkable
								checkedKeys={selectIdData}
								onCheck={onCheck}
								checkStrictly={checkStrictly}
								treeData={menuSource}
								fieldNames={{
									title: 'name',
									key: 'id',
								}}
							/>
						</Panel>
					</Collapse>
					<div className={styles.wrap}>
						<Button
							type="primary"
							htmlType="submit"
							onClick={onFinish}>
							保存
						</Button>
						<Button
							onClick={() => {
								history.go(-1)
							}}>
							取消
						</Button>
					</div>
				</div>
			</div>
		)
	},
)

export default connect(({user}: any) => ({
	user,
}))(addDom)
